package com.foo.Servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.foo.DataProvider.ProviderClient;
import com.foo.DataReciever.DataReciever;
import com.foo.Entity.RealTimeData;
import com.foo.Entity.TickerInfoData;
import com.foo.Writer.WriterClient;
import com.foo.Constants.Constants;
import com.foo.Constants.UIMessages;
import com.sun.tools.jxc.apt.Const;

/**
 * Servlet implementation class SpatialDataServlet
 */
public class SpatialServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	TickerInfoData[] tickerdata = null;
	String[] trialstring = null; 
	String fileName;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SpatialServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		boolean downloadRequired = false;
		boolean readData = false;
		String filetype = "";
		WriterClient writer = new WriterClient();

		try
		{
			String actbutton = request.getParameter("buttonHit");
			if(request.getParameter("TXT.x") != null)
			{
				filetype ="TXT";
				downloadRequired = true;
			}
			else if(request.getParameter("CSV.x")!= null)
			{
				filetype ="CSV";
				downloadRequired = true;
			}
			else if(request.getParameter("JSON.x")!= null)
			{
				filetype ="JSON";
				downloadRequired = true;
			}		
			else if(request.getParameter("XML.x")!= null)
			{
				filetype ="XML";
				downloadRequired = true;
			}
			if(downloadRequired)
			{
				TickerInfoData[] sessionData = (TickerInfoData[])session.getAttribute("SpatialData");
				if(sessionData == null)
				{
					readData = true;
				}
			}
			else
			{
				readData = true;
			}
			if(readData) // Read Data from file
			{
				String sortBased = request.getParameter("SortBased");
				String paramName = "";
				//Get the secord Sort Value
				if(sortBased.equalsIgnoreCase("Country"))
				{
					paramName = request.getParameter("Country");
				}
				else if(sortBased.equalsIgnoreCase("State"))
				{
					paramName = request.getParameter("State");
				}
				else if(sortBased.equalsIgnoreCase("Industry"))
				{
					paramName = request.getParameter("Industry");
				}
				else if(sortBased.equalsIgnoreCase("Sector"))
				{
					paramName = request.getParameter("Sector");
				}
				DataReciever receive = new DataReciever();
				
				//Send the message to the EJB component based on the data entered
				ProviderClient client = new ProviderClient();
				client.getData(sortBased,paramName,null,null,null);
				
				trialstring = receive.readtickerinfodata();
				
				if(trialstring != null)
				{
					System.out.println("values length: " +trialstring.length);
					int tickerarraysize = (trialstring.length / 8); 
					string_to_object(trialstring,tickerarraysize);	
				}
				else
				{
					System.out.println("No message returned");
				}
				if(tickerdata != null)
				{
					session.setAttribute("SpatialData", tickerdata);
					session.setAttribute("SpatialDataString",trialstring);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
					dispatcher.forward(request, response);
				}
				else
				{
					request.setAttribute("ServerMessage", UIMessages.NO_RECORD);
					RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
					dispatcher.forward(request, response);
				}
				System.out.println("Exited Loop");
				
				
			}
			else if(downloadRequired) // Download File
			{
				if(trialstring ==null || trialstring.length == 0)
				{
					trialstring = (String[])session.getAttribute("SpatialDataString");
				}
				if(trialstring!=null && trialstring[0] != "" && filetype !=null)
				{
					if(filetype.equals("CSV"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();
						fileName =Constants.FILE_PATH + "data.csv";
						//client.generateCSV(fileName, trialstring,"Spatial");
						writer.selectfile(fileName, trialstring,"Spatial");

						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("TXT"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//CSVWriterClient client = new CSVWriterClient();
						
						fileName =Constants.FILE_PATH + "data.txt";
						//client.generateCSV(fileName, trialstring,"Spatial");
						writer.selectfile(fileName, trialstring,"Spatial");

						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("JSON"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//JSONWriterClient client = new JSONWriterClient();
						fileName =Constants.FILE_PATH + "data.json";
						//client.generateJSON(fileName, trialstring,"Spatial");
						writer.selectfile(fileName, trialstring,"Spatial");

						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
					else if(filetype.equals("XML"))
					{
						System.out.println("Requested file of type " +filetype +" is being generated.");
						//XMLWriterClient client = new XMLWriterClient();
						fileName =Constants.FILE_PATH + "data.xml";
						//client.generateJSON(fileName, trialstring,"Spatial");
						writer.selectfile(fileName, trialstring,"Spatial");

						System.out.println("File Generate and stored in workspace folder: ");
						
						//Read the file and Get it as a download Option
						if(new File(fileName).exists())
						response = downloadData(response,fileName);
						
						RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
						dispatcher.forward(request, response);
						System.out.println("File Generate and stored in workspace folder: ");
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			request.setAttribute("ServerMessage", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/spatial.jsp");
			dispatcher.forward(request, response);
		}
	}
	public HttpServletResponse downloadData(HttpServletResponse response,String fileName) throws Exception
	{
		try
		{
			if(new File(fileName).exists())
			{
				File fileContent = new File(fileName);
				InputStream inputStream = new FileInputStream(fileContent);
				long length = fileContent.length();
				
			 if (length > Integer.MAX_VALUE) {
			        // File is too large
			    }
			 response.reset();
				response.setContentType("application/file");
				String name = new File(fileName).getName();
				System.out.println("File Name is :" + name);
				response.setHeader("Content-disposition","attachment; filename=" +name);
				   
			    byte[] bytes = new byte[(int)length];
	
			    int offset = 0,numRead = 0;
			    while (offset < bytes.length
			           && (numRead=inputStream.read(bytes, offset, bytes.length-offset)) >= 0) {
			        offset += numRead;
			        response.getOutputStream().write(bytes, 0, numRead);
			    }
	
			    if (offset < bytes.length) {
			        throw new IOException("Could not completely read file data.txt");
			    }
	
			    inputStream.close();
			}
			response.getOutputStream().flush();
			return response;
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	public void string_to_object(String[] trialstring, int tickerarraysize) throws Exception
	{
		try
		{
			int j=0;
			tickerdata = new TickerInfoData[tickerarraysize];
			for(int i =0;i<trialstring.length;i+=8)
			{
				if(trialstring[i].equals("") || trialstring[i] == null)
				{
					System.out.println("No more data to print");
					break;
				}
				else
				{
					TickerInfoData ticker=new TickerInfoData();
					ticker.setTicker_symbol(trialstring[i+1]);
					System.out.println("Data 1 "+ ticker.getTicker_symbol());
					ticker.setCompany(trialstring[i+2]);				
					ticker.setSector_name(trialstring[i+3]);			
					ticker.setIndustry(trialstring[i+4]);				
					ticker.setCountry(trialstring[i+5]);			
					ticker.setState(trialstring[i+6]);	
					ticker.setMarket_cap(Double.parseDouble(trialstring[i+7]));
					tickerdata[j]=ticker;		
					j=j+1;
	
				}
			}
			System.out.println("Conversion to objectdata was successful");
		}
		catch(Exception e)
		{
			throw e;
		}
	}
	
	public void object_to_string(TickerInfoData[] objectData) throws Exception
	{
		try
		{
			int j =0;
			trialstring = new String[objectData.length];
			if(objectData[j].equals("") || objectData[j] == null)
			{
				System.out.println("No more data to print");
				return;
			}
			for(int i =0;i<objectData.length * 7;i+=7)
			{
				
				trialstring[i] += objectData[j].getTicker_symbol(); 
				trialstring[i + 1] += objectData[j].getCompany();
				trialstring[i + 2] += objectData[j].getSector_name();
				trialstring[i + 3] += objectData[j].getIndustry();
				trialstring[i + 4] += objectData[j].getCountry();
				trialstring[i + 5] += objectData[j].getState();
				trialstring[i + 6] += objectData[j].getMarket_cap();
						j++;
			}
			System.out.println("Conversion to objectdata was successful");
		}
		catch(Exception e)
		{
			throw e;
		}
	}

}
